import 'dart:io';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/entity/conversation_list_entity.dart';
import 'package:oramemo/entity/upload_voice_entity.dart';
import 'package:oramemo/entity/voice_record_detail_entity.dart';
import 'package:oramemo/entity/voice_record_entity.dart';

import '../network/dio_client.dart';
import '../config/api_config.dart';
import '../models/api_response.dart';
import '../models/call_record.dart';
import '../models/voice_record.dart';

class RecordRepository {
  final DioClient _client = DioClient();

  Future<ApiResponse<ConversationListEntity>> getCallRecords({
    required int page,
    required int size,
    String? deviceId,
    DateTime? startTime,
    DateTime? endTime,
  }) async {
    final response = await _client.request(
      path: ApiConfig.callRecords,
      method: 'GET',
      queryParameters: {
        'pageNum': page,
        'pageSize': size,
        if (deviceId != null) 'deviceId': deviceId,
        if (startTime != null) 'startTime': startTime.toIso8601String(),
        if (endTime != null) 'endTime': endTime.toIso8601String(),
      },
    );
    return ApiResponse.fromJson(
      response.data,
      (data) => ConversationListEntity.fromJson(data),
    );
  }

  Future<ApiResponse<VoiceRecordEntity>> getVoiceRecords({
    required int page,
    required int size,
    String? voiceType,
    String? deviceId,
    DateTime? startTime,
    DateTime? endTime,
    String? voiceFolderId,
  }) async {
    final response = await _client.request(
      path: ApiConfig.voiceRecords,
      method: 'GET',
      queryParameters: {
        'pageNum': page,
        'pageSize': size,
        'voiceType': voiceType,
        'voiceFolderId': voiceFolderId,
        if (deviceId != null) 'deviceId': deviceId,
        if (startTime != null) 'startTime': startTime.toIso8601String(),
        if (endTime != null) 'endTime': endTime.toIso8601String(),
      },
    );
    return ApiResponse.fromJson(
      response.data,
      (data) => VoiceRecordEntity.fromJson(data),
    );
  }

  Future<ApiResponse<VoiceRecordDetailEntity>> getVoiceRecordDetail(
      String id) async {
    final response = await _client.request(
      path: '${ApiConfig.voiceRecordDetail}$id',
      method: 'GET',
    );
    return ApiResponse.fromJson(
      response.data,
      (data) => VoiceRecordDetailEntity.fromJson(data),
    );
  }

  Future<ApiResponse<UploadVoiceEntity>> uploadVoiceRecord(File file) async {
    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(file.path),
    });

    final response = await _client.request(
      path: ApiConfig.uploadVoice,
      method: 'POST',
      data: formData,
    );
    return ApiResponse.fromJson(
        response.data, (data) => UploadVoiceEntity.fromJson(data));
  }
}
